package ldh.im.fxbase.util;

import ldh.im.util.ConfigUtil;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

public class DbFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(DbFactory.class);

    private static DbFactory instance = null;
    private volatile DataSource dataSource = null;

    private DbFactory() {
        String currentDir = getCurrentFile();
        dataSource = initDb(currentDir);
    }

    public static DbFactory getInstance() {
        if (instance == null) {
            synchronized (DbFactory.class) {
                if (instance == null) {
                    LOGGER.info("new dbFactory, instance2: " + instance);
                    instance = new DbFactory();
                    LOGGER.info("new dbFactory end!");
                }
            }
        }
        return instance;
    }

    private DataSource initDb(String dbFilePath) {
        try {
            LOGGER.info("init db, dir:" + dbFilePath);
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName("org.h2.Driver");
            dataSource.setUrl(String.format("jdbc:h2:%s;AUTO_RECONNECT=TRUE", dbFilePath));
            dataSource.setUsername("im");
            dataSource.setPassword("im123456");
            dataSource.setInitialSize(5);
            dataSource.setMaxTotal(100);
            return dataSource;
        } catch (Exception e) {
            LOGGER.info("init db error:" + e.getMessage());
            throw new RuntimeException("连接数据库失败!", e);
        }
    }

    private static String getCurrentFile() {
//        String dir = System.getProperty("user.dir") + File.separator + "data" + File.separator + "db" + File.separator;
        String dir = ConfigUtil.getRoot() + File.separator + "db" + File.separator;
        LOGGER.info("get current File: " + dir);
        File file = new File(dir);
        if(!file.exists()) {
            file.mkdir();
        }
        return dir + ConfigUtil.getString("im.name");
    }

    public QueryRunner buildQueryRunner(){
        return new QueryRunner(dataSource);
    }

    public Connection getConnection() throws SQLException {
        Connection connection = dataSource.getConnection();
        return connection;
    }

    public void close(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }
}
